package com.fly.easy.queue.croe;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.fly.easy.queue.common.MessageEntity;

public class FlyMessageQueue {
	private Logger logger = Logger.getLogger(FlyMessageQueue.class);

	// 队列大小
	public static final int QUEUE_MAX_SIZE = 10000000;

	
	// 阻塞队列
	private BlockingQueue<MessageEntity> blockingQueue = new LinkedBlockingQueue<MessageEntity>(QUEUE_MAX_SIZE);



	/**
	 * 消息入队(队列满阻塞)
	 * 
	 * @param alarmMessageVO
	 * @return
	 */
	public boolean push(MessageEntity alarmMessageVO) {
		boolean ispush =true;
		try {
			this.blockingQueue.put(alarmMessageVO);
		} catch (InterruptedException e) {
			return false;
		}
		logger.debug("Thread:"+Thread.currentThread().getName()+"-size:" + size());
		return ispush;
	}
	
	/**
	 * 非阻塞消息入队(非安全)
	 * 
	 * @param alarmMessageVO
	 * @return
	 */
	public boolean offer(MessageEntity alarmMessageVO) {
		boolean ispush =	this.blockingQueue.offer(alarmMessageVO);
		
		logger.debug("Thread:"+Thread.currentThread().getName()+"-size:" + size());
		return ispush;
	}
	
	
	/**
	 * 非阻塞消息入队(非安全)
	 * 
	 * @param alarmMessageVO
	 * @return
	 */
	public boolean offer(MessageEntity alarmMessageVO,long timeout) {
		boolean ispush;
		try {
			ispush = this.blockingQueue.offer(alarmMessageVO, timeout, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			return false;
		}
		logger.debug("Thread:"+Thread.currentThread().getName()+"-size:" + size());
		return ispush;
	}


	/**
	 * 消息出队
	 * 
	 * @return
	 */
	public MessageEntity poll() {
		MessageEntity result = null;
		try {
			result = this.blockingQueue.take();
			logger.debug("Thread:"+Thread.currentThread().getName()+"-size:" + size());
		} catch (InterruptedException e) {
			logger.error("poll error", e);
		}
		return result;
	}

	/**
	 * 获取队列大小
	 * 
	 * @return
	 */
	public int size() {
		return this.blockingQueue.size();
	}
}
